const express = require('express');
const db = require('../config/db');

const router = express.Router();

// 获取用户列表（支持分页和搜索）
router.get('/users', async (req, res) => {
  try {
    const { page = 1, pageSize = 8, search = '' } = req.query;
    const offset = (page - 1) * pageSize;
    
    // 构建查询条件
    let query = 'SELECT id, name, account, amount, role, status, avatar FROM user_manage';
    let countQuery = 'SELECT COUNT(*) as total FROM user_manage';
    const params = [];
    
    if (search) {
      query += ' WHERE name LIKE ? OR account LIKE ?';
      countQuery += ' WHERE name LIKE ? OR account LIKE ?';
      params.push(`%${search}%`, `%${search}%`);
    }
    
    query += ' ORDER BY id LIMIT ? OFFSET ?';
    params.push(parseInt(pageSize), parseInt(offset));
    
    // 查询用户数据
    const [rows] = await db.execute(query, params);
    
    // 查询总数
    const [countResult] = await db.execute(countQuery, params.slice(0, search ? 2 : 0));
    const total = countResult[0].total;
    
    res.json({
      code: 200,
      message: '获取用户列表成功',
      data: {
        list: rows,
        pagination: {
          currentPage: parseInt(page),
          pageSize: parseInt(pageSize),
          total: total
        }
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 根据ID获取用户详情
router.get('/users/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [rows] = await db.execute(
      'SELECT id, name, account, amount, role, status, avatar FROM user_manage WHERE id = ?',
      [id]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    
    res.json({
      code: 200,
      message: '获取用户详情成功',
      data: rows[0]
    });
  } catch (error) {
    console.error('获取用户详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 创建新用户
router.post('/users', async (req, res) => {
  try {
    const { name, account, amount, role, status, avatar } = req.body;
    
    // 检查账号是否已存在
    const [existing] = await db.execute(
      'SELECT id FROM user_manage WHERE account = ?',
      [account]
    );
    
    if (existing.length > 0) {
      return res.status(400).json({
        code: 400,
        message: '账号已存在'
      });
    }
    
    // 插入新用户
    const [result] = await db.execute(
      'INSERT INTO user_manage (name, account, amount, role, status, avatar) VALUES (?, ?, ?, ?, ?, ?)',
      [name, account, amount, role, status, avatar]
    );
    
    res.status(201).json({
      code: 201,
      message: '创建用户成功',
      data: {
        id: result.insertId,
        name,
        account,
        amount,
        role,
        status,
        avatar
      }
    });
  } catch (error) {
    console.error('创建用户失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 更新用户信息
router.put('/users/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, account, amount, role, status, avatar } = req.body;
    
    // 检查用户是否存在
    const [existing] = await db.execute(
      'SELECT id FROM user_manage WHERE id = ?',
      [id]
    );
    
    if (existing.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    
    // 更新用户信息
    await db.execute(
      'UPDATE user_manage SET name = ?, account = ?, amount = ?, role = ?, status = ?, avatar = ? WHERE id = ?',
      [name, account, amount, role, status, avatar, id]
    );
    
    res.json({
      code: 200,
      message: '更新用户成功',
      data: {
        id: parseInt(id),
        name,
        account,
        amount,
        role,
        status,
        avatar
      }
    });
  } catch (error) {
    console.error('更新用户失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 删除用户
router.delete('/users/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查用户是否存在
    const [existing] = await db.execute(
      'SELECT id FROM user_manage WHERE id = ?',
      [id]
    );
    
    if (existing.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    
    // 删除用户
    await db.execute('DELETE FROM user_manage WHERE id = ?', [id]);
    
    res.json({
      code: 200,
      message: '删除用户成功'
    });
  } catch (error) {
    console.error('删除用户失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

module.exports = router;